<template>
    <div class="role-list">
        <div class="toolbar">
            <el-input
                v-model="searchKeyword"
                placeholder="请输入角色名称搜索"
                clearable
                @input="handleSearch"
                style="width: 300px"
            >
                <template #prefix>
                    <el-icon><search /></el-icon>
                </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">新增角色</el-button>
        </div>

        <el-table
            :data="roleList"
            style="width: 100%"
            v-loading="loading"
        >
            <el-table-column prop="roleName" label="角色名称" />
            <el-table-column prop="roleDescribe" label="角色描述" show-overflow-tooltip />
            <el-table-column prop="roleStatus" label="状态" width="100">
                <template #default="{ row }">
                    <el-tag :type="row.roleStatus === 1 ? 'success' : 'danger'">
                        {{ row.roleStatus === 1 ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="180" />
            <el-table-column label="操作" width="150" fixed="right">
                <template #default="{ row }">
                    <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
                    <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination-container">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="total"
                layout="total, sizes, prev, pager, next"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>

        <role-form
            v-model="dialogVisible"
            :type="dialogType"
            :role-data="currentRole"
            :permission-list="permissionList"
            @success="handleSuccess"
        />
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { List as GetList, Delete, details, type UserRole } from '@/apis/role'
import { List as GetPermissionList, type UserPermission } from '@/apis/permission'
import RoleForm from './RoleForm.vue'

// 状态变量
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const currentRole = ref<UserRole>()
const roleList = ref<UserRole[]>([])
const permissionList = ref<UserPermission[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')

// 获取权限列表
const fetchPermissionList = async () => {
    try {
        const data = await GetPermissionList({
            keyword: ''
        })
        permissionList.value = data.list
    } catch (error) {
        console.error('获取权限列表失败:', error)
        ElMessage.error('获取权限列表失败')
    }
}

// 获取角色列表
const fetchList = async () => {
    loading.value = true
    try {
        const data = await GetList({
            page: currentPage.value,
            pageSize: pageSize.value,
            keyword: searchKeyword.value.trim()
        })
        roleList.value = data.list
        total.value = data.total
    } catch (error) {
        console.error('获取角色列表失败:', error)
        ElMessage.error('获取角色列表失败')
    } finally {
        loading.value = false
    }
}

// 搜索处理
let searchTimer: NodeJS.Timeout | null = null
const handleSearch = () => {
    if (searchTimer) {
        clearTimeout(searchTimer)
    }
    searchTimer = setTimeout(() => {
        currentPage.value = 1 // 重置页码
        fetchList()
    }, 300)
}

// 新增角色
const handleAdd = () => {
    dialogType.value = 'add'
    currentRole.value = undefined
    dialogVisible.value = true
}

// 编辑角色
const handleEdit = async (row: UserRole) => {
    dialogType.value = 'edit'
    try {
        const detail = await details(row.uUID)
        currentRole.value = detail
        dialogVisible.value = true
    } catch (error) {
        console.error('获取角色详情失败:', error)
        ElMessage.error('获取角色详情失败')
    }
}

// 删除角色
const handleDelete = async (row: UserRole) => {
    try {
        await ElMessageBox.confirm('确定要删除该角色吗？', '提示', {
            type: 'warning'
        })
        await Delete(row.uUID)
        ElMessage.success('删除成功')
        fetchList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }
}

// 分页处理
const handleSizeChange = (val: number) => {
    pageSize.value = val
    fetchList()
}

const handleCurrentChange = (val: number) => {
    currentPage.value = val
    fetchList()
}

// 操作成功回调
const handleSuccess = () => {
    fetchList()
}

// 初始化
onMounted(() => {
    fetchPermissionList()
    fetchList()
})
</script>

<style scoped lang="scss">
.role-list {
    .toolbar {
        margin-bottom: 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .pagination-container {
        margin-top: 16px;
        display: flex;
        justify-content: flex-end;
    }
}
</style> 